from scapy.all import *  
from example_api import * # from dzy/code/example_api.py
#注意，example_api.py的 from datetime import datetimedef 和 get_encodeStr(username, password): 之间加上 username = "root" 和 password = "root"
def toIpv4(num):
    nums = [str((num >> ((24 - i * 8))) & 0xFF) for i in range(4)] 
    return ".".join(nums)  
def toIpv6(num):
    nums = [hex((num >> (112 - i * 16)) & 0xFFFF)[2:] for i in range(8)] 
    return ":".join(nums)  
    
def packet_callback(packet):   
    if (IP in packet or IPv6 in packet) and TCP in packet:  
        tcp_flags = packet[TCP].flags 
        if tcp_flags == 0x3F:   
            data = packet[TCP].load  
            print(f"data: {data}")
            print(f"len(data): {len(data)}") 
            if len(data)<128:
            	pass
            tag_id = int.from_bytes(data[0:8], byteorder='big')
            id_hash = int.from_bytes(data[8:40], byteorder='big')
            data_id = int.from_bytes(data[40:48], byteorder='big')
            sent_num = int.from_bytes(data[48:56], byteorder='big')
            temp = int.from_bytes(data[56:64], byteorder='big')
            src_id = temp >> 36
            dst_id = (temp >> 8)&0xfffffff
            level = (temp >> 6)&0x3
            data_mode = (temp >> 1)&0x1f
            protocol_type = temp & 0x1
            src_ip = int.from_bytes(data[64:80], byteorder='big')
            dst_ip = int.from_bytes(data[80:96], byteorder='big')
            tag_hash = int.from_bytes(data[96:128], byteorder='big')
            print(f"tag_id: {hex(tag_id)}") 
            print(f"id_hash: {hex(id_hash)}") 
            print(f"data_id: {hex(data_id)}") 
            print(f"sent_num: {hex(sent_num)}") 
            print(f"src_id: {hex(src_id)}") 
            print(f"dst_id: {hex(dst_id)}") 
            print(f"level: {hex(level)}") 
            print(f"data_mode: {hex(data_mode)}") 
            print(f"protocol_type: {hex(protocol_type)}") 
            if IP in packet:
                print(f"src_ip: {toIpv4(src_ip)}") 
                print(f"dst_ip: {toIpv4(dst_ip)}") 
            else:
                print(f"src_ip: {toIpv6(src_ip)}") 
                print(f"dst_ip: {toIpv6(dst_ip)}") 
            print(f"tag_hash: {hex(tag_hash)}") 
            if IP in packet:
                insert_tablet(hex(tag_id), hex(id_hash), hex(data_id), hex(sent_num), hex(src_id), hex(dst_id), hex(level), hex(data_mode), hex(protocol_type), toIpv4(src_ip), toIpv4(dst_ip))
            else:
                insert_tablet(hex(tag_id), hex(id_hash), hex(data_id), hex(sent_num), hex(src_id), hex(dst_id), hex(level), hex(data_mode), hex(protocol_type), toIpv6(src_ip), toIpv6(dst_ip))
            query_data()

create_database()
create_timeseries() 
sniff(prn=packet_callback, store=False)